package com.ruoyi.business.controller.app;

import com.ruoyi.business.service.IWsdLeaveRecordsService;
import com.ruoyi.business.service.IWsdLeavesService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdLeaveRecords;
import com.ruoyi.common.core.domain.vo.wsdLeavesVO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 请假审批记录小程序
 *
 * @author ruoyi
 * @date 2024-04-16
 */
@RestController
@RequestMapping("wx_records")
public class WxAppWsdLeaveRecordsController extends BaseController {

    @Autowired
    private IWsdLeavesService wsdLeavesService;

    @Autowired
    private IWsdLeaveRecordsService wsdLeaveRecordsService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 审批请假请求
     */
    @Log(title = "审批请假请求", businessType = BusinessType.UPDATE)
    @PutMapping("/approveLeave")
    public AjaxResult approveLeave(@RequestBody WsdLeaveRecords WsdLeaveRecords) {
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        Long userId = user.getUserId();
        WsdLeaveRecords.setSchoolApproverId(userId);
        WsdLeaveRecords.setSchoolId(schoolId);
        //根据用户id查询角色是否可以审核请假
        List<SysRole> sysRoles = roleService.selectRolesUserByUserId(user.getUserId());
        List<Long> roleIds = sysRoles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        //根据roleIds查询角色是否可以审核请假
        sysRoles = roleService.selectRolesByRoleIds(roleIds);
        //把sysRoles中的canReviewLeave拿出来(0=不可以，1可以)
        boolean canReviewLeave = sysRoles.stream().anyMatch(sysRole -> Objects.equals(sysRole.getCanReviewLeave(), Constants.STATUS));
        if (!canReviewLeave){
            return AjaxResult.warn("您没有权限审核请假");
        }
        return toAjax(wsdLeaveRecordsService.appoveLeave(WsdLeaveRecords));
    }

    /**
     * 查询审核和未审核请假记录列表
     */
    @GetMapping("/list")
    public TableDataInfo listAuditing(Boolean auditing) {
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        startPage();
        List<wsdLeavesVO> list = wsdLeavesService.selectWsdLeaveslistAuditing(auditing,schoolId);
        if (list.size()>0){
            Collections.reverse(list);
        }
        return getDataTable(list);
    }

}
